﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data;

namespace PGE.Models.Repositorios
{
    public class BaseRepository<TEntity> : IRepositorio<TEntity> where TEntity : class
    {
        private DbContext context;
        private DbSet<TEntity> dbSet;

        public BaseRepository(DbContext context)
        {
            this.context = context;
            this.dbSet = context.Set<TEntity>();
        }

        public void Insert(TEntity entity)
        {
            this.dbSet.Add(entity);
        }

        public void Delete(TEntity entity)
        {
            this.dbSet.Remove(entity);
        }

        public void Update(int entityId, TEntity entity)
        {
            var entry = context.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                TEntity attachedEntity = dbSet.Find(entityId);
                if (attachedEntity != null)
                {
                    var attachedEntry = context.Entry(attachedEntity);
                    attachedEntry.CurrentValues.SetValues(entity);
                }
                else
                {
                    entry.State = EntityState.Modified;
                }
            }
        }

        public IQueryable<TEntity> Queryable
        {
            get { return dbSet; }
        }

        public TEntity Find(int id)
        {
            return dbSet.Find(id);
        }

        public DbSet<TEntity> DbSet
        {
            get { return dbSet; }
        }
    }
}